package com.ehome.serial.camera.example

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.ParcelFileDescriptor
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.blankj.utilcode.util.GsonUtils
import com.ehome.serial.camera.BA330CameraManager
import com.ehome.serial.v2.example.R
import java.io.File
import kotlin.concurrent.thread
import kotlin.experimental.xor

class MainActivity : AppCompatActivity() {
    val ba330CameraManager = BA330CameraManager.instance

    lateinit var serialNumberEditText: AppCompatEditText
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        serialNumberEditText = findViewById(R.id.serial_number)
    }

    fun takeRawPicture(view: View) {

        thread(start = true) {
            ba330CameraManager.takeFluoRawPicture(
                10000,
                File("/sdcard/fluo_${10000}.raw"),
                100
            )

//        thread(start = true) {
//            ba330CameraManager.takeGoldRawPicture(1000u, "/sdcard/gold.raw");
//        }
//        lifecycleScope.launch(Dispatchers.IO) {
//            try {
//                val data = Maybe.create { e ->
//                    ba330CameraManager.takeRawPicture(object : BA330CameraListener {
//
//                        override fun onComplete(data: ByteArray) {
//                            Log.d("BA330CameraManager", "takeRawPicture onComplete")
//                            Log.d("BA330CameraManager", "data -> " + data.size)
//                            e.onSuccess(data)
//                            e.onComplete()
//                        }
//
//                    })
//                }
//                    .subscribeOn(Schedulers.computation())
//                    .blockingGet()
//
//                val yuvImage = YuvImage(data, ImageFormat.NV21, 1280, 1072, null)
//                val out = ByteArrayOutputStream()
//                yuvImage.compressToJpeg(Rect(0, 0, 1280, 1072), 100, out)
//                val jpegData = out.toByteArray()
//                BitmapFactory.decodeByteArray(jpegData, 0, jpegData.size)
//
////                FileIOUtils.writeFileFromBytesByStream("/sdcard/image.jpeg", jpegData, false)
//            } catch (e: Exception) {
//                Log.e("BA330CameraManager", "takeRawPicture exception -> ${e.message}")
//            }
//        }
        }
    }

    fun takeYuvPicture(view: View) {
        thread(start = true) {
            ba330CameraManager.takeYuvPicture(target = File("/sdcard/qrcode.yuv"))
        }

//        lifecycleScope.launch(Dispatchers.IO) {
//            try {
//                val data = Maybe.create { e ->
//                    ba330CameraManager.takeYuvPicture(object : BA330CameraListener {
//
//                        override fun onComplete(data: ByteArray) {
//                            Log.d("BA330CameraManager", "takeYuvPicture onComplete")
//                            Log.d("BA330CameraManager", "data -> " + data.size)
//                            e.onSuccess(data)
//                            e.onComplete()
//                        }
//
//                    })
//                }
//                    .subscribeOn(Schedulers.computation())
//                    .blockingGet()
//
//                val yuvImage = YuvImage(data, ImageFormat.NV21, 1280, 1072, null)
//                val out = ByteArrayOutputStream()
//                yuvImage.compressToJpeg(Rect(0, 0, 1280, 1072), 100, out)
//                val jpegData = out.toByteArray()
//                BitmapFactory.decodeByteArray(jpegData, 0, jpegData.size)
//
////                FileIOUtils.writeFileFromBytesByStream("/sdcard/image.jpeg", jpegData, false)
//            } catch (e: Exception) {
//                Log.e("BA330CameraManager", "takeYuvPicture exception -> ${e.message}")
//            }
//        }
    }
    //1280x1072


    fun takeRawSequencePicture(view: View) {
        thread(start = true) {
            for (exposureTime in BA330CameraManager.EXPOSURE_SEQUENCE) {
                ba330CameraManager.takeFluoRawPicture(
                    exposureTime,
                    File("/sdcard/fluo_${exposureTime}.yuv"),
                    20
                )
            }
        }
    }

    fun getSerialNumber(view: View) {
        thread(start = true) {
            val deviceInfo = ba330CameraManager.getDeviceInfo()
            Log.d("MainActivity", GsonUtils.toJson(deviceInfo))
        }
    }

    fun setSerialNumber(view: View) {
        thread(start = true) {
            val serialNumber = serialNumberEditText.text.toString()
            ba330CameraManager.setSerialNumber(serialNumber)
        }
    }

    fun setCalibrationFile(view: View) {
        thread(start = true) {
            ba330CameraManager.setCalibrationFile(File("/sdcard/test.zip"))
        }
    }

    fun getCalibrationFile(view: View) {
        thread(start = true) {
            ba330CameraManager.getCalibrationFile(File("/sdcard/CalibrationFile.zip"))
        }
    }

    fun getKitSate(view: View) {
        thread(start = true) {
//            while (true) {
                val result = ba330CameraManager.getKitSate()
                Log.d("MainActivity", "getKitSate -> ${result}")
//                Thread.sleep(1000)
//            }
        }
    }

    fun getLogFile(view: View) {
        thread(start = true) {
            while (true) {
                ba330CameraManager.getLogFile(File("/sdcard/ba330.log"))
                Thread.sleep(10000)
            }
        }
    }

    @SuppressLint("SdCardPath")
    fun takeFluoSequencePicture(view: View) {
        val sequence = linkedMapOf<Int, File>(
            15000 to File("/sdcard/test_1.raw"),
            22000 to File("/sdcard/test_2.raw"),
            33000 to File("/sdcard/test_3.raw"),
            50000 to File("/sdcard/test_4.raw"),
            75000 to File("/sdcard/test_5.raw"),
            113000 to File("/sdcard/test_6.raw"),
            170000 to File("/sdcard/test_7.raw"),
            256000 to File("/sdcard/test_8.raw"),
            384000 to File("/sdcard/test_9.raw"),
            576000 to File("/sdcard/test_10.raw"),
            864000 to File("/sdcard/test_11.raw"),
            1297000 to File("/sdcard/test_12.raw"),
            1946000 to File("/sdcard/test_13.raw"),
            2919000 to File("/sdcard/test_14.raw"),
            4378000 to File("/sdcard/test_15.raw"),
            6568000 to File("/sdcard/test_16.raw"),
            9852000 to File("/sdcard/test_17.raw"),
            14778000 to File("/sdcard/test_18.raw"),
            22168000 to File("/sdcard/test_19.raw"),
            33252000 to File("/sdcard/test_20.raw"),
            49878000 to File("/sdcard/test_21.raw"),
            74818000 to File("/sdcard/test_22.raw"),
            112227000 to File("/sdcard/test_23.raw"),
            112227001 to File("/sdcard/test_24.raw")
        )

        thread(start = true) {
//            while (true) {
            ba330CameraManager.takeFluoSequencePicture(sequence)
//                Thread.sleep(10000)
//            }
        }
    }

    fun update(view: View) {
        thread(start = true) {
            ba330CameraManager.setOtaFile(File("/sdcard/update.zip"))
            ba330CameraManager.update()
        }
    }

    fun reboot(view: View) {
        thread(start = true) {
            ba330CameraManager.reboot()
        }
    }

    fun setFactoryQCFile(view: View) {
        thread(start = true) {
            ba330CameraManager.setFactoryQCFile(File("/sdcard/test.zip"))
        }
    }

    fun getFactoryQCFile(view: View) {
        thread(start = true) {
            ba330CameraManager.getFactoryQCFile(File("/sdcard/test11.zip"))
        }
    }

    fun selfCheck(view: View) {
        thread(start = true) {
            ba330CameraManager.selfCheck()
        }
    }

    fun setTimestamp(view: View) {
        thread(start = true) {
            ba330CameraManager.setTimeStamp()
        }
    }

}